package org.jeecg.modules.carLedger.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.carInformationUpload.service.ICarInformationUploadService;
import org.jeecg.modules.carLedger.entity.CarLedger;
import org.jeecg.modules.carLedger.service.ICarLedgerService;
import org.jeecg.modules.carRecord.service.ICarRecordService;
import org.jeecg.modules.inPlantUpload.service.IInPlantUploadService;
import org.jeecg.modules.noRoadUpload.service.INoRoadUploadService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 进出厂车辆电子台账
 * @Author: jeecg-boot
 * @Date:   2024-07-23
 * @Version: V1.0
 */
@Api(tags="进出厂车辆电子台账")
@RestController
@RequestMapping("/carLedger/carLedger")
@Slf4j
public class CarLedgerController extends JeecgController<CarLedger, ICarLedgerService> {
	@Autowired
	private ICarLedgerService carLedgerService;
	@Autowired
	private IInPlantUploadService inPlantUploadService;
	@Autowired
	private INoRoadUploadService noRoadUploadService;
	@Autowired
	private ICarRecordService carRecordService;
	@Autowired
	private ICarInformationUploadService carInformationUploadService;

	@Value("${jeecg.path.upload}")
	private String upLoadPath;
	
	/**
	 * 分页列表查询
	 *
	 * @param carLedger
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="进出厂车辆电子台账-分页列表查询", notes="进出厂车辆电子台账-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CarLedger carLedger,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CarLedger> queryWrapper = QueryGenerator.initQueryWrapper(carLedger, req.getParameterMap());
		Page<CarLedger> page = new Page<CarLedger>(pageNo, pageSize);
		IPage<CarLedger> pageList = carLedgerService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @ApiOperation(value="进出厂车辆电子台账-对外-分页列表查询", notes="进出厂车辆电子台账-对外-分页列表查询")
	 @GetMapping(value = "/m/list")
	 public Result<?> mQueryPageList(CarLedger carLedger,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<CarLedger> queryWrapper = QueryGenerator.initQueryWrapper(carLedger, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 Page<CarLedger> page = new Page<CarLedger>(pageNo, pageSize);
		 IPage<CarLedger> pageList = carLedgerService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	@ApiOperation(value="进出厂车辆电子台账-引领型企业-分页列表查询", notes="进出厂车辆电子台账-引领型企业-分页列表查询")
	@GetMapping(value = "/leadingList")
	public Result<?> leadingList(CarLedger carLedger,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CarLedger> queryWrapper = QueryGenerator.initQueryWrapper(carLedger, req.getParameterMap());
		queryWrapper.eq("leading_enterprise", 1);
		Page<CarLedger> page = new Page<CarLedger>(pageNo, pageSize);
		IPage<CarLedger> pageList = carLedgerService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param carLedger
	 * @return
	 */
	@AutoLog(value = "进出厂车辆电子台账-添加")
	@ApiOperation(value="进出厂车辆电子台账-添加", notes="进出厂车辆电子台账-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CarLedger carLedger) {
		carLedgerService.save(carLedger);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param carLedger
	 * @return
	 */
	@AutoLog(value = "进出厂车辆电子台账-编辑")
	@ApiOperation(value="进出厂车辆电子台账-编辑", notes="进出厂车辆电子台账-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CarLedger carLedger) {
		carLedgerService.updateById(carLedger);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出厂车辆电子台账-通过id删除")
	@ApiOperation(value="进出厂车辆电子台账-通过id删除", notes="进出厂车辆电子台账-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		carLedgerService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "进出厂车辆电子台账-批量删除")
	@ApiOperation(value="进出厂车辆电子台账-批量删除", notes="进出厂车辆电子台账-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.carLedgerService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出厂车辆电子台账-通过id查询")
	@ApiOperation(value="进出厂车辆电子台账-通过id查询", notes="进出厂车辆电子台账-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CarLedger carLedger = carLedgerService.getById(id);
		if(carLedger==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(carLedger);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param carLedger
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarLedger carLedger) {
        return super.exportXls(request, carLedger, CarLedger.class, "进出厂车辆电子台账");
    }

	@RequestMapping(value = "/leadingExportXls")
	public ModelAndView leadingExportXls(HttpServletRequest request, CarLedger carLedger) {
		// Step.1 组装查询条件
		QueryWrapper<CarLedger> queryWrapper = QueryGenerator.initQueryWrapper(carLedger, request.getParameterMap());
		queryWrapper.eq("leading_enterprise", 1);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<CarLedger> pageList = carLedgerService.list(queryWrapper);
		List<CarLedger> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "进出厂车辆电子台账"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, CarLedger.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams=new ExportParams("进出厂车辆电子台账报表", "导出人:" + sysUser.getRealname(), "进出厂车辆电子台账");
		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarLedger.class);
    }

	private String getId(CarLedger item) {
		try {
			return PropertyUtils.getProperty(item, "id").toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@ApiOperation(value="进出厂车辆电子台账-客户端-查询排放统计", notes="进出厂车辆电子台账-客户端-查询排放统计")
	@GetMapping("/m/getCharts")
	public Result<?> mGetCharts(@RequestParam(name="start",required=false) String start,
								@RequestParam(name="end",required=false) String end) {
		QueryWrapper<CarLedger> wrapper = new QueryWrapper<>();
		wrapper.select("SUM(CASE WHEN evn_type = 'D' THEN 1 ELSE 0 END) AS new_energy_count",
				"SUM(CASE WHEN evn_type = '6' THEN 1 ELSE 0 END) AS guo6_count",
				"SUM(CASE WHEN evn_type = '5' THEN 1 ELSE 0 END) AS guo5_count",
				"SUM(CASE WHEN evn_type = '4' THEN 1 ELSE 0 END) AS guo4_count",
				"SUM(CASE WHEN evn_type = '3' THEN 1 ELSE 0 END) AS guo3_count");
		wrapper.ge(StringUtils.isNotBlank(start), "create_time", start);
		wrapper.le(StringUtils.isNotBlank(end), "create_time",  end);
		List<Map<String, Object>> maps = carLedgerService.listMaps(wrapper);
		return Result.OK(maps);
	}

	@GetMapping("/getCharts")
	 public Result<?> getCharts(HttpServletRequest req) {
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		QueryWrapper<CarLedger> wrapper = new QueryWrapper<>();
		wrapper.select("SUM(CASE WHEN evn_type = 'D' THEN 1 ELSE 0 END) AS new_energy_count",
				"SUM(CASE WHEN evn_type = '6' THEN 1 ELSE 0 END) AS guo6_count",
				"SUM(CASE WHEN evn_type = '5' THEN 1 ELSE 0 END) AS guo5_count",
				"SUM(CASE WHEN evn_type IN ('4', '3', '2', '1') THEN 1 ELSE 0 END) AS lower_guo4_count");
		wrapper.between("create_time", start, end);
		List<Map<String, Object>> maps = carLedgerService.listMaps(wrapper);
		wrapper.clear();
		wrapper.select("SUM(CASE WHEN fuel_type = 'A' THEN 1 ELSE 0 END) AS gasoline_count",
				"SUM(CASE WHEN fuel_type = 'C' THEN 1 ELSE 0 END) AS electric_count",
				"SUM(CASE WHEN fuel_type = 'B' THEN 1 ELSE 0 END) AS diesel_count",
				"SUM(CASE WHEN fuel_type = 'E' THEN 1 ELSE 0 END) AS natural_gas_count",
				"SUM(CASE WHEN fuel_type NOT IN ('A', 'C', 'B', 'E') THEN 1 ELSE 0 END) AS other_fuel_count");
		wrapper.between("create_time", start, end);
		List<Map<String, Object>> fuelType = carLedgerService.listMaps(wrapper);
		maps.addAll(fuelType);
		return Result.OK(maps);
	}

	@GetMapping("/getFleetCharts")
	public Result<?> getFleetCharts(HttpServletRequest req){
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		List<Map<String, Object>> fleetCharts = carLedgerService.getFleetCharts(start, end);
		return Result.OK(fleetCharts);
	}

	@GetMapping("/getGoodCharts")
	public Result<?> getGoodCharts(HttpServletRequest req) {
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		List<Map<String, Object>> fleetCharts = carLedgerService.getGoodCharts(start, end);
		return Result.OK(fleetCharts);
	}

	@GetMapping("/getDashboardData")
	public Result<?> getDashboardData() {
		int todayCount = carLedgerService.getTodayCount();
		int monthCount = carLedgerService.getMonthCount();
		int inPlantCount = inPlantUploadService.count();
		int noRoadCount = noRoadUploadService.count();
		int todayInCount = carRecordService.getTodayInCount();
		int todayUploadCount = carInformationUploadService.getTodayUploadCount();
		int todayUnUploadCount = carInformationUploadService.getTodayUnUploadCount();
		Map<String, Integer> map = new HashMap<>();
		map.put("todayCount", todayCount);
		map.put("monthCount", monthCount);
		map.put("inPlantCount", inPlantCount);
		map.put("noRoadCount", noRoadCount);
		map.put("todayInCount", todayInCount);
		map.put("todayUploadCount", todayUploadCount);
		map.put("todayUnUploadCount", todayUnUploadCount);
		return Result.OK(map);
	}

	@GetMapping("/getChartsLeading")
	public Result<?> getChartsLeading(HttpServletRequest req) {
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		QueryWrapper<CarLedger> wrapper = new QueryWrapper<>();
		wrapper.select("SUM(CASE WHEN evn_type = 'D' THEN 1 ELSE 0 END) AS new_energy_count",
				"SUM(CASE WHEN evn_type = '6' THEN 1 ELSE 0 END) AS guo6_count",
				"SUM(CASE WHEN evn_type = '5' THEN 1 ELSE 0 END) AS guo5_count",
				"SUM(CASE WHEN evn_type IN ('4', '3', '2', '1') THEN 1 ELSE 0 END) AS lower_guo4_count");
		wrapper.between("create_time", start, end);
		wrapper.eq("leading_enterprise", 1);
		List<Map<String, Object>> maps = carLedgerService.listMaps(wrapper);
		wrapper.clear();
		wrapper.select("SUM(CASE WHEN fuel_type = 'A' THEN 1 ELSE 0 END) AS gasoline_count",
				"SUM(CASE WHEN fuel_type = 'C' THEN 1 ELSE 0 END) AS electric_count",
				"SUM(CASE WHEN fuel_type = 'B' THEN 1 ELSE 0 END) AS diesel_count",
				"SUM(CASE WHEN fuel_type = 'E' THEN 1 ELSE 0 END) AS natural_gas_count",
				"SUM(CASE WHEN fuel_type NOT IN ('A', 'C', 'B', 'E') THEN 1 ELSE 0 END) AS other_fuel_count");
		wrapper.between("create_time", start, end);
		wrapper.eq("leading_enterprise", 1);
		List<Map<String, Object>> fuelType = carLedgerService.listMaps(wrapper);
		maps.addAll(fuelType);
		return Result.OK(maps);
	}

	@GetMapping("/getFleetChartsLeading")
	public Result<?> getFleetChartsLeading(HttpServletRequest req){
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		List<Map<String, Object>> fleetCharts = carLedgerService.getFleetChartsLeading(start, end);
		return Result.OK(fleetCharts);
	}

	@GetMapping("/getGoodChartsLeading")
	public Result<?> getGoodChartsLeading(HttpServletRequest req) {
		String start = req.getParameter("start");
		String end = req.getParameter("end");
		List<Map<String, Object>> fleetCharts = carLedgerService.getGoodChartsLeading(start, end);
		return Result.OK(fleetCharts);
	}

}
